package vip.xiaonuo.hontu.listener.handle.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.hontu.issued.response.ClusterTaskDetail;
import vip.xiaonuo.hontu.listener.handle.HandleService;
import vip.xiaonuo.hontu.listener.handle.model.HongTuPushData;
import vip.xiaonuo.modular.clustertaskresult.entity.ClusterTaskResult;
import vip.xiaonuo.modular.clustertaskresult.service.ClusterTaskResultService;
import vip.xiaonuo.modular.htpushdata.entity.HtPushData;
import vip.xiaonuo.modular.htpushdata.service.HtPushDataService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ClusterDataHandleService implements HandleService<List<ClusterTaskDetail>> {

    @Resource
    private HtPushDataService pushDataService;

    @Resource
    private ClusterTaskResultService clusterTaskResultService;

    @Override
    public void handle(HtPushData data) {
        try{
            String content = data.getValue();
            HongTuPushData pushData = JSON.parseObject(content,HongTuPushData.class);
            List<ClusterTaskDetail> details = JSON.parseArray(pushData.getData(), ClusterTaskDetail.class);
            if(data.getStatus()==0){
                this.saveData(pushData, details);
            }
            data.setStatus(1);
        }catch (Exception e){
            data.setFailReason(ExceptionUtils.getMessage(e));
            data.setStatus(2);
        }finally {
            // 聚类结果的数据不推送，只当前服务自己处理
            data.setPushFlag(Boolean.TRUE);
            pushDataService.saveOrUpdate(data);
        }
    }

    @Override
    public void saveData(List<ClusterTaskDetail> clusterTaskDetails) {

    }


    public void saveData(HongTuPushData data ,List<ClusterTaskDetail> clusterTaskDetails) {
        for(ClusterTaskDetail detail : clusterTaskDetails){
            ClusterTaskResult result = new ClusterTaskResult() ;
            BeanUtil.copyProperties(detail,result);
            result.setPushFlag(false);
            result.setDeviceId(data.getDeviceId());
            result.setDataType(data.getDataType());
            List<ClusterTaskResult> resultDb = clusterTaskResultService.list(new LambdaQueryWrapper<ClusterTaskResult>()
                    .eq(ClusterTaskResult :: getProfileId, detail.getProfileId())
                    .eq(ClusterTaskResult :: getDeviceId , data.getDeviceId())
                    .eq(ClusterTaskResult :: getDataType , data.getDataType()));
            if(!resultDb.isEmpty()){
                result.setId(resultDb.get(0).getId());
                result.setPushFlag(resultDb.get(0).getPushFlag());
            }
            clusterTaskResultService.saveOrUpdate(result);
        }
    }


}
